package com.x.erp.manage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.x.erp.dao.CarAuthDao;
import com.x.erp.dao.DetectionDao;
import com.x.erp.model.Car;
import com.x.erp.model.CarAuth;
import com.x.erp.model.CarLog;
import com.x.erp.model.Detection;
import com.x.framework.exception.BusinessException;
import com.x.framework.manage.BaseManage;

@Service
public class CarAuthManage extends BaseManage {
	
	@Autowired
	private DetectionDao detectionDao;// 检测单dao
	
	@Autowired
	private CarAuthDao carAuthDao;// 车辆认证dao
	/**
	 * 新增认证证书信息
	 * 
	 * @param carAuth
	 * @return
	 * @throws Exception
	 */
	public CarAuth insertCarAuth(CarAuth carAuth) throws Exception {
		Car car = carAuth.getCar();
		CarAuth temp = createCarAuth(car);
		temp.setCreateUserId(carAuth.getCreateUserId());
		carAuth = this.insert(temp);
		
		if (this.update(car) != 1) {
			throw new BusinessException("新增车辆认证证书、修改车辆状态出错");
		}
		// 记录日志信息
		List<CarLog> carLogs = car.getCarLogs();
		if (carLogs != null) {
			for (CarLog carLog : carLogs) {
				this.insert(carLog);
			}
		}
		return carAuth;
	}
	/**
	 * 创建认证证书
	 * @param car
	 * @throws Exception
	 */
	private CarAuth createCarAuth(Car car) throws Exception {
		CarAuth carAuth = new CarAuth();
		// 认证证书格式：市场编号后三位+日期（八位）+ 序号（三位） 例子：00120180321001
		Detection detectionTemp = new Detection();
		detectionTemp.setCarId(car.getCarId());
		detectionTemp = detectionDao.selectDetection(detectionTemp);
		carAuth.setCarId(detectionTemp.getCarId());
		carAuth.setAuthCreateTime(new Date());
		carAuth.setDetectionId(detectionTemp.getDetectionId());
		carAuth.setMarketId(detectionTemp.getMarketId());
		carAuth.setShopId(detectionTemp.getCar().getShopId());
		
		carAuth.setAuthCompany("潍坊泰华车港机动车鉴定评估有限公司");
		
		StringBuilder authNo = new StringBuilder();
		// 市场编号后3位
		String marketCode = detectionTemp.getMarket().getMarketCode();
		String marketCode3 = marketCode.substring(marketCode.length() - 3);
		authNo.append(marketCode3);
		// 当前日期8位
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String format = sdf.format(date);
		authNo.append(format);
		// 序号3位
		CarAuth carAuthTemp = new CarAuth();
		carAuthTemp.setMarketId(detectionTemp.getMarketId());
		int currentNum = carAuthDao.selectCurrentNum(carAuthTemp, marketCode3 + format + "%");
		String currentNumStr = "000" + currentNum;
		String currentNo = currentNumStr.substring(currentNumStr.length() - 3);
		authNo.append(currentNo);
		carAuth.setAuthNo(authNo.toString());
		return carAuth;
	}
}
